package com.yukh.framework.base.net.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class Client {
	
	public static void sendToMessage(String req, String tpdu, boolean isAcsii){
		
	}
	
	public static void sendToMessage(String req){
		ChannelFactory channelFactory = new NioClientSocketChannelFactory(
				Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
		ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
		clientBootstrap.getPipeline().addLast("handler", new MyHandler());
		clientBootstrap.setOption("tcpNoDelay", true);
		clientBootstrap.setOption("keepAlive", true);
		
		ChannelFuture future = clientBootstrap.connect(new InetSocketAddress("192.168.126.211", 8629));
		future.awaitUninterruptibly();
		if (future.isSuccess()) {
			 System.out.println("Connect Success!");
		} else {
			future.getCause().printStackTrace();
		}
		
//		req = "02006020048000C088111741005001040017322031000000009901200031324D3030303031303130303220202020202020202020313536260000000000000000111111111111103944363530313232";
		
		byte[] iso8583Data = BCDASCII.fromASCIIToBCD(req, 0, req.length(), false);
		byte[] commData = new byte[iso8583Data.length + 4];
		String len = String.format("%1$04d", iso8583Data.length);
		byte[] asciiLengh = len.getBytes();
		System.arraycopy(asciiLengh, 0, commData, 0 , 4);
		System.arraycopy(iso8583Data, 0, commData, 4 , iso8583Data.length);
		
		String logStr = BCDASCII.fromBCDToASCIIString(commData, 0, commData.length * 2, false);
		System.out.println("ABC SZPOS DATA SEND TO BANK[" + logStr + "].");
		
		Channel channel = future.getChannel();
		ChannelBuffer channelBuffer = ChannelBuffers.buffer(commData.length);
		channelBuffer.writeBytes(commData);
		channel.write(channelBuffer);
		
		channel.getCloseFuture().awaitUninterruptibly();
		
		channelFactory.releaseExternalResources();
	}
	
	private static class MyHandler extends SimpleChannelHandler {

		@Override
		public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			super.channelClosed(ctx, e);
		}

		@Override
		public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
			super.channelConnected(ctx, e);
		}

		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
			ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
			System.out.println(buffer.readableBytes());
			byte[] dataFromBank = new byte[buffer.readableBytes()];
			buffer.readBytes(dataFromBank);

			StringBuffer lengthBytes = new StringBuffer();
			lengthBytes.append((char)dataFromBank[0]);
			lengthBytes.append((char)dataFromBank[1]);
			lengthBytes.append((char)dataFromBank[2]);
			lengthBytes.append((char)dataFromBank[3]);
			int len = Integer.parseInt(lengthBytes.toString());
			byte[] iso8583Data = new byte[len];
			System.arraycopy(dataFromBank, 4, iso8583Data, 0, len);
			String logStr = BCDASCII.fromBCDToASCIIString(iso8583Data, 0, len * 2, false);
			System.out.println("DATA FROM BANK [" + logStr + "].");
			
//			int len = (respData[0] & 0x0ff) * 256 + (respData[1] & 0x0ff);
//			byte[] data = new byte[len];
//			System.arraycopy(respData, 2, data, 0, len);
//			System.out.print("Lenght:" + len);
//			System.out.println(",Data:" + new String(data));
			
			e.getChannel().close();
		}
	}
	
	public static void main(String[] args) {
	}
}
